package cn.wenhaha.app.job.service.imp;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.wenhaha.app.job.manager.SyncMappingJob;
import cn.wenhaha.app.job.service.JobControlService;
import cn.wenhaha.common.db.bean.SysMapping;
import cn.wenhaha.job.DynamicJob;
import cn.wenhaha.job.ScheduleDynamicUtil;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 控制定时任务实现类
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2022-12-09 21:46
 */
@Service
public class JobControlServiceImp implements JobControlService {

    private static final Logger LOG = LoggerFactory.getLogger(JobControlServiceImp.class);

    @Resource
    private AutowireCapableBeanFactory capableBeanFactory;



    @Override
    public boolean close(String id,String createById) {
        ScheduleDynamicUtil.deleteJob( Long.parseLong(id),createById);
        return true;
    }

    @Override
    public void testRun(SysMapping sysMapping) {
        SyncMappingJob syncMappingJob = new SyncMappingJob(sysMapping);
        capableBeanFactory.autowireBean(syncMappingJob);
        ThreadUtil.execute(syncMappingJob::run);
    }

    @Override
    public Trigger.TriggerState state(String id, String createById) {
        try {
            return ScheduleDynamicUtil.statusJob(Long.parseLong(id),createById);
        } catch (SchedulerException e) {
            LOG.error("查询job状态出错",e);
            return Trigger.TriggerState.ERROR;
        }
    }


    @Override
    public boolean start(SysMapping sysMapping) {
        DynamicJob dynamicJob = new DynamicJob(sysMapping.getCron(),
                Long.parseLong(sysMapping.getId()),  new SyncMappingJob(), sysMapping.getCreateBy());
        dynamicJob.setData(MapUtil.builder(SysMapping.class.getName(),(Object)sysMapping).build());
        ScheduleDynamicUtil.addJob(dynamicJob);
        return true;
    }
}
